package com.lanou3g.ptp.filecontrol.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.lanou3g.ptp.filecontrol.service.PackedFileService;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class PackedFileServiceImpl implements PackedFileService {
    @Override
    public byte[] packedByStudent(Long taskId, Long studentId, String fileName) throws Exception {

        String parent = "/Users/mylovelyziwei/IdeaProjects/ptp/ptp-filecontrol-service/target/FileContorl/resource";

        String newPath = parent + "/" + taskId + "/" + studentId;

        File[] files = new File(newPath).listFiles();

        byte[] buf = new byte[1024];

        String newName = newPath + "/" + fileName + ".zip";

        FileInputStream fileInputStream = null;


        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(newName));


        for (File file : files) {
            fileInputStream = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zipOutputStream.putNextEntry(zipEntry);

            int len;
            while ((len = fileInputStream.read(buf)) != -1) {
                zipOutputStream.write(buf, 0, len);
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }

        fileInputStream.close();
        zipOutputStream.closeEntry();
        zipOutputStream.close();


        File file = new File(newName);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();




        return bytes;
    }
}



